#include "Buffer.h"
#include <string.h>
#include "assert.h"
#include "stdio.h"

Buffer::Buffer(){
	buf = new char[MAX_BUFFER_SIZE];//可以是config
	len = 0;
}
Buffer::~Buffer(){
	if(buf != NULL){
		delete[] buf;
		buf = NULL;
		len = 0;
	}
}

int Buffer::pushData(const char *_b, int _s){

	assert( _s > 0 );
	if( _s < 0 ){
		return -1;
	}
	if( len + _s > MAX_BUFFER_SIZE ){
		return -2;
	}
	memcpy(buf, _b, _s);
	len += _s;
	return _s;
}

int Buffer::popData(char *_b, int _s){
	assert( _s > 0 );
	if( _s > 0 && _b != NULL ){
		if( _s > len ){
			_s = len;
		}
		memcpy(_b, buf, _s);
		len -= _s;
		if( len != 0 ){
			memmove(buf+_s, buf, len); 
		}
	}
	return _s;
}

int Buffer::mustPopData(char *_b, int _s){
	assert( _s > 0 );
	if( _s > 0 && _b != NULL ){
		if( _s > len ){
			return -1;
		}
		memcpy(_b, buf, _s);
		len -= _s;
		if( len != 0 ){
			memmove(buf+_s, buf, len); 
		}
	}
	return _s;
}

int Buffer::lookData(char *_b, int _s){
	assert( _s > 0 );
	if( _s > 0 && _b != NULL ){
		if( _s > len ){
			_s = len;
		}
		memcpy(_b, buf, _s);
	}
	return _s;
}

const char * Buffer::getBufferPtr(){
	return buf;
}

void Buffer::skipData(int skip){
	assert( skip > 0 );
	if( skip <= 0 || skip > len ){
		return ;
	}
	memmove(buf, buf+skip, len-skip);
	len -= skip;
}

void Buffer::print(){

	for(int i=0; i<len; i++){
		printf("%x ", buf[i]);
	}
	printf("\n");

}

int Buffer::size(){
	return len;
}

